package com.tyc.async;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 类描述
 *
 * @author tyc
 * @version 1.0
 * @date 2023-03-09 11:58:45
 */
public class Master {
    // 任务队列
    protected Queue<Object> workQueue = new ConcurrentLinkedQueue<>();
    // 工作线程
    protected Map<String,Thread> workerMap = new HashMap<>();
    // 子任务处理结果集
    protected Map<String,Object> resultMap = new ConcurrentHashMap<>();

    // 任务是否处理完
    public boolean isComplete(){
        for (Map.Entry<String, Thread> threadEntry : workerMap.entrySet()) {
            if(threadEntry.getValue().getState() != Thread.State.TERMINATED){
                return false;
            }
        }
        return true;
    }

    public Master(Worker worker,int num){
        worker.setResultMap(resultMap);
        worker.setWorkQueue(workQueue);
        for (int i = 0; i < num; i++) {
            workerMap.put(Integer.toString(i),new Thread(worker));
        }
    }

    //提交一个任务
    public void submit(Object job){
        workQueue.add(job);
    }
    //返回子任务结果集
    public Map<String,Object> getResultMap(){
        return resultMap;
    }
    //开始运行所有的Worker进程进行处理
    public void execute(){
        for(Map.Entry<String, Thread> entry:workerMap.entrySet()){
            entry.getValue().start();
        }
    }
}
